﻿using MvcWechat.Common;
using MvcWechat.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;

namespace MvcWechat.Controllers
{
    public class BaseController : Controller
    {
        //
        //序列化加上用户提交的信息
        public string GetInputJson(bool isAddParam = false, Dictionary<string, object> dict = null)
        {
            var inputJson = ManagerJson.ToJson(ControllerContext.RequestContext.HttpContext.Request.InputStream);
            if (inputJson == "" || inputJson.Contains("params=")) inputJson = "{}";//前端有传params的可能，也过滤下

            Dictionary<object, object> str = AddInputJson(isAddParam, dict, inputJson);
            if (inputJson.StartsWith("{") && inputJson.EndsWith("}"))
            {
                inputJson = JsonConvert.SerializeObject(str);
            }
            if (inputJson.StartsWith("[") && inputJson.EndsWith("]"))
            {
                List<Dictionary<object, object>> listStr = JsonConvert.DeserializeObject<List<Dictionary<object, object>>>(inputJson);
                listStr.Add(str);
                inputJson = JsonConvert.SerializeObject(listStr);
            }
            //inputJson = nHtmlFilter.filter(inputJson);
            return inputJson;
        }

        private Dictionary<object, object> AddInputJson(bool isAddParam, Dictionary<string, object> dict, string inputJson)
        {
            Dictionary<object, object> str = JsonConvert.DeserializeObject<Dictionary<object, object>>(inputJson);
            if (isAddParam)
            {
                str.Add("ActiveIP", MyUrlHelper.GetIPAddress(System.Web.HttpContext.Current));
                str.Add("OperationUserId", "客户" + HttpContext.Session["CustomerID"]);
                str.Add("HttpUrl", System.Web.HttpContext.Current.Request.Url.Authority.ToLower());

                //新增操作系统，浏览器版本
                str.Add("Browser", Request.Browser.Browser + Request.Browser.Version);
                str.Add("OpeartionSystem", Environment.OSVersion.VersionString);
            }
            if (dict != null)
            {
                foreach (var item in dict)
                {
                    str.Add(item.Key, item.Value);
                }
            }
            str.Add("TagKey", CommonPage.getKey());
            return str;
        }

        public Dictionary<string, object> GetInputDict()
        {
            return JsonConvert.DeserializeObject<Dictionary<string, object>>(GetInputJson());
        }
        public string ParsePartUrlByToken(string url)
        {
            string token = XcxConfigs.XcxTokenHelper.GetToken();
            return string.Format(url, token);
        }
        //带一级的key的InputJson
        public string GetParentKeyInputJson()
        {
            //SubmitOrders  GetInventoryInfos 
            Dictionary<string, object> dict = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(CommonPage.GetConfigSettings().PublicParentUrl))
                dict.Add("PublicParentUrl", CommonPage.GetConfigSettings().PublicParentUrl); 
            if (!string.IsNullOrEmpty(CommonPage.GetConfigSettings().ParentKey))
                dict.Add("ParentKey", CommonPage.GetConfigSettings().ParentKey);
            if(!string.IsNullOrEmpty( CommonPage.GetConfigSettings().ErJiMark))
                dict.Add("ErJiMark", CommonPage.GetConfigSettings().ErJiMark);
            return GetInputJson(true, dict);
        }
         
        /// <summary>
        /// 通过临时key得到父类key（基类），系统类型（上级是批发还是零售），及自己真实的供应商key
        /// </summary>
        /// <param name="key"></param>
        /// <param name="supplierKey"></param>
        /// <param name="sysType"></param>
        /// <param name="secondSn"></param>
        public  void GetAllKeysByPreKey(string key, out string supplierKey, out string sysType, out string secondSn)
        {
            if (key.Contains("__"))
            {
                var allKey = key.Split(new string[] { "__" }, StringSplitOptions.None); //按类型与key分割
                var newKey = allKey[0].Split('_'); //key
                                                   //父类key
                supplierKey = newKey[0];
                //系统类型
                sysType = allKey[1];
                //真实的供应商key
                secondSn = newKey[1];
            }
            else
            {
                supplierKey = key;
                //系统类型
                sysType = "";
                //真实的供应商key
                secondSn = "";
            }
        }
        public void GetPostParam()
        {
            var _params = ControllerContext.RequestContext.HttpContext.Request.InputStream;
            if (_params != null && _params.Length > 0)
            {
                var param = HttpUtility.UrlDecode(ManagerJson.ToJson(ControllerContext.RequestContext.HttpContext.Request.InputStream).Replace("params=", ""), System.Text.Encoding.UTF8);
                ViewBag.Param = param;
            }
            else
            {
                ViewBag.Param = "null";
            }
        }
    }
}
